<?php

defined('BASEPATH') OR exit('No direct script access allowed');
//---------------------------------------------------------
//|	发现模块
//---------------------------------------------------------
//| @author rable
//---------------------------------------------------------
class Find extends MY_Controller {
	
	/**
	 * 分类模型
	 * @var ConsumerFindCategoryModel
	 */
	public $mCategory;
	
	/**
	 * 发现模型
	 * @var ConsumerFindModel
	 */
	public $mFind;

    /**
     * 朋友圈模型
     * @var ConsumerFriendsCircleModel
     */
	public $mFriends;
	/**
	 * 模型
	 * @var ConsumerFindAttributeModel
	 */
	public $mAttribute;
	
	public function __construct(){
		parent::__construct();
		$this->loadModel('ConsumerFindCategoryModel', 'mCategory', 'consumer');
		$this->loadModel('ConsumerFindModel', 'mFind', 'consumer');
		$this->loadModel('ConsumerFindAttributeModel', 'mAttribute', 'consumer');
	}

	
	/**
	 * 获取发现分类
	 */
	public function getFindCategory(){
		
		$tA = $this->mCategory->getList();
		if ( ! $tA){
			$this->appReturn(0,'数据为空');
		}
		array_unshift($tA, array('id'=>'0','name'=>'全部','attr_cate_id' => '0'));
		$this->appReturn(1,'',$tA);
	}
	
	/**
	 * 获取发现列表
	 */
	public function getFindList(){
		//表单验证
		$vConf = array(
				array('page', '分页', 'required|is_natural_no_zero'),//
				array('sort', '排序方式', 'required|is_natural_no_zero'),//
				//array('category_id', '分类id', 'required|is_natural_no_zero'),//
// 				array('county', '区域id', 'required|is_natural_no_zero'),//
				
		);
		$this->formDataValidation($vConf);
		
		$page	= post('page');
		$sort 	= post('sort');
		$county = (int)post('county');
		$categoryId = (int)post('category_id');
		
		$latitude	= post('latitude');
		$longitude 	= post('longitude');

		$tCategory = array(
				'name'=>'全部',
				'icon'=>getDefaultImg(),
		);
		
		if ($categoryId){
			$tinfo = $this->mCategory->getInfo($categoryId);
		
			$tCategory['name'] = isset($tinfo['name'])?$tinfo['name']:"";
			$tCategory['icon'] = isset($tinfo['icon'])?$tinfo['icon']:"";
			/**
			 * 是否收藏
			 */
			$tCategory['is_Collection'] = "1";//没有关注
			$sessionid = decode(post('sessionid'));
			$tUser = $this->mUser->getInfoBySessionid($sessionid,1);
			if ($tUser){
				if ($this->mUser->hasCollection($tUser['id'], $categoryId, 3)){
					$tCategory['is_Collection'] = "2";//有关注
				}
			}
		}
		
		//获取关注总量
		$tCategory['total_collection'] = (string)$this->mUser->getCollectionTotal($categoryId,5);
		//获取该分类总帖子数
		$tCategory['total_find'] = (string)$this->mFind->getFindCategoryTotal($categoryId);
		
		$tData['base'] = $tCategory;
		//发现列表
		$tA = $this->mFind->appGetList($county,$sort,$page,0,0,$latitude,$longitude,$categoryId);
	
		$tData['list'] = $tA;
		if ( ! $tA){
			$this->appReturn(1,'没有一篇发现',$tData);
		}
		$this->appReturn(1,'',$tData);
	}
	
	/**
	 * 发布/编辑发现消息
	 */
	public function saveFind(){
		//表单验证
		$vConf = array(
				array('title', '标题', 'required'),//
				array('content', '内容', 'required'),//
				array('category_id', '分类id', 'required|is_natural_no_zero'),
				array('nickname', '联系人', 'required'),
				array('mobile', '电话', 'required|valid_mobile'),
				array('county_name', '省市区名称', 'required'),
				array('address', '详细地址', 'required'),
				array('province', '省id', 'required|is_natural_no_zero'),
				array('city', '市id', 'required|is_natural_no_zero'),
				array('county', '区id', 'required|is_natural_no_zero'),
				array('latitude', '经度', 'required'),
				array('longitude', '纬度', 'required'),
		);
		$this->formDataValidation($vConf);
		
		$id				= trim(post('id'));//发现id
		$title			= trim(post('title'));
		$content 		= trim(post('content'));
		$categoryId 	= post('category_id');
		$nickname 		= trim(post('nickname'));
		$mobile 		= post('mobile');
		$county_name	= trim(post('county_name')); //省市区名
		$address 		= trim(post('address'));
		$province 		= post('province');
		$city 			= post('city');
		$county 		= post('county');
		$latitude		= trim(post('latitude'));
		$longitude		= trim(post('longitude'));
		
		$tFind = array();
		if ($id){
			//验证是否存在
			$tFind = $this->mFind->getInfo($id,true);
			if (! $tFind){
				$this->appReturn(0,'该信息已经不存在');
			}
		}
		
		$tattribute 	= trim(post('attribute'));
		$attribute = json_decode($tattribute,true);
		if ($tattribute && ! is_array($attribute)){
			$this->appReturn(0,'特殊属性格式错误');
		}
		
		$imgs 			= trim(post('imgs')); //图片json
		$images = json_decode($imgs,true);
		if ($imgs && ! is_array($images)){
			$this->appReturn(0,'图片格式错误');
		}
		
		//$attribute = json_decode('[{"attr_id":"1","attr_value":"aaa"},{"attr_id":"4","attr_value":"aaa"}]',true);
		
		if ( ! $tInfo = $this->mCategory->getInfo($categoryId)){
			$this->appReturn(0,'分类不存在');
		}
		
		if ($tInfo['attr_cate_id'] && ! is_array($attribute)){
			$this->appReturn(0,'请设置特殊属性');
		}
		
		$this->db->trans_begin();//开启事务
		
		if ($id){
			$data = array(
// 					'consumer_id'=>$this->userId,
// 					'category_id'=>$categoryId,
					'title'=>base64_encode($title),
					'content'=>base64_encode($content),
// 					'pic'=>json_encode(array()),
					'province'=>$province,
					'city'=>$city,
					'county'=>$county,
					'county_name'=>$county_name,
					'address'=>$address,
					'latitude'=>$latitude,
					'longitude'=>$longitude,
					'nickname'=>$nickname,
					'mobile'=>$mobile,
// 					'read_number'=>0,
 					'status'=>1,
// 					'addtime'=>time(),
// 					'is_delete'=>1,//未删除
			);
			
			$query = $this->mFind->save($data,$id);
			if (! $query){
				$this->db->trans_rollback();
				$this->appReturn(0,'发布失败');
			}
		}else{
		
			$data = array(
					'consumer_id'=>$this->userId,
					'category_id'=>$categoryId,
					'title'=>base64_encode($title),
					'content'=>base64_encode($content),
					'pic'=>json_encode(array()),
					'province'=>$province,
					'city'=>$city,
					'county'=>$county,
					'county_name'=>$county_name,
					'address'=>$address,
					'latitude'=>$latitude,
					'longitude'=>$longitude,
					'nickname'=>$nickname,
					'mobile'=>$mobile,
					'read_number'=>0,
					'status'=>2,
					'addtime'=>time(),
					'is_delete'=>1,//未删除
			);
			
			$tId = $this->mFind->save($data);
			if (! $tId){
				$this->db->trans_rollback();
				$this->appReturn(0,'发布失败');
			}
		}
		
		$tId = $id?:$tId;
		
		//特殊属性
		if (is_array($attribute) && !empty($attribute)){
			$tAttr = array();
			foreach ($attribute as $k=>$v){
				$tAttr[] = array(
						'attr_id'=>$v['attr_id'],
						'attr_value'=>$v['attr_value'],
						'find_id'=>$tId,
				);
			}
		
			if ( ! $this->mAttribute->saveBatchAttribute($tAttr,$id)){
				$this->db->trans_rollback();
				$this->appReturn(0,'保存失败');
			}
		}
		
		/**
		 * 上传图片
		 */
		if ( ! empty($images)){
			$tImgs = array();
			$path = 'uploads/find/'.$this->userId.'/'.$tId.'/';
			$n = 0;
			try{
				$result = moveImage($images,$path);
			}catch (Exception $e){
				$this->appReturn(0,"图片异常".$e->getMessage());
			}
			
			foreach ($result as $k=>$v){
				$result[$k] = str_replace(base_url(), "", $v);
			}
			
			//把旧图片找出来
			if ($id){
				//验证是否存在
				$tFindImgs = json_decode($tFind['pic'],true); 
				//循环，查找是否还在最新的地址里面
				foreach ($tFindImgs as $k=>$v){
					if ( ! in_array($v, $result)){
						//是否有 ? 去掉
						if (stripos($v, '?') !== false){
							$v = strstr($v, '?', true);
						}
						
						if (! file_exists($v)){
							continue;
						}
						//获取文件名
						$tI = explode('/', $v);
						$filename = $tI[count($tI)-1];
						$sm = str_replace($filename, 'sm/'.$filename, $v);
						$xs = str_replace($filename, 'xs/'.$filename, $v);
						//不在里面 删除
						unlink($v);
						unlink($sm);
						unlink($xs);
					}
				}
			}
			
			if ( ! $this->mFind->save(array('pic'=>json_encode($result)),$tId)){
				$this->db->trans_rollback();
				$this->appReturn(0,'保存失败');
			}
		}
		$this->db->trans_commit();
		
		if ( ! $id){
            $this->loadModel('ConsumerExperienceValueModel', 'mExperience','consumer');
            $this->loadModel('ConsumerMallModel', 'mMall','consumer');
			//发布时 编辑时除外
	        $this->mMall->_addIntegral(4, $this->userId, $this->userIntegral);
	        $this->mExperience->_addExperienceValue(3, $this->userId, $this->userExperienceValue);
			$this->appReturn(1,'发布成功',array('id'=>$tId));
		}
		$this->appReturn(1,'编辑成功',array('id'=>$tId));
	}
	
	/**
	 * 上传图
	 */
	public function upload(){
		if ( ! $_FILES){
			$this->appReturn(0,'文件不存在');
		}
		
		$tImgs = array();
		$path = 'uploads/find/temp/'.$this->userId;
		
		foreach ($_FILES as $k=>$v){
			$result = imageUpload($path, $k,uniqid().rand(0,9999),true);
			if ( ! $result['status']){
				foreach ($tImgs as $ik=>$iv){
					unlink($iv);
				}
				$this->appReturn(0,'上传失败');
			}
			
			$tImgs[] = $result['data'];
		}
		
		foreach ($tImgs as $k=>&$v){
			$v = getImage($v,'og');
		}
		
		$this->appReturn(1,'',$tImgs);
	}
	
	
	/**
	 * 获取发现详情
	 */
	public function getFindInfo(){
		//表单验证
		$vConf = array(
				array('find_id', '发现id', 'required|is_natural_no_zero'),
		);
		
		$this->formDataValidation($vConf);
		
		$findId = trim(post('find_id'));
		
		$tA = $this->mFind->getInfo($findId);
		
		$tUser = array();
		$sessionid = decode(post('sessionid'));
		if ($sessionid){
			$tUser = $this->mUser->getInfoBySessionid($sessionid);
		}
		
		if ($tA){
			//获取特殊值
			$this->loadModel('ConsumerFindAttributeModel', 'mAttribute','consumer');
			$tA['is_approval'] = "1";
			if ($tUser && $this->mFind->hasApproval($findId, $this->userId)){
				$tA['is_approval'] = "2";
			}

			$tA['is_collection'] = "1";
			if ($tUser && $this->mUser->hasCollection($this->userId,$findId,2)){
				$tA['is_collection'] = "2";
			}
			
			if ( ! $tUser){
				$tA['mobile'] = substr($tA['mobile'], 0,3).'****'.substr($tA['mobile'], -4);
			}
			$tA['attr'] = $this->mAttribute->getAttributeValueList($findId);
			unset($tA['latitude']);
			unset($tA['longitude']);
			unset($tA['status']);
			unset($tA['name']);
			unset($tA['province']);
			unset($tA['city']);
			unset($tA['county']);
		
			//获取推荐
			$total = $this->mFind->getFindTotal($tA['consumer_id']);
			$tA['desc'] = '最近发布了'.$total.'条';
			
			//获取推荐
			$tA['relevance'] = $this->mFind->appGetList(0,3,1,5);//获取浏览最多，第1页
			
			$tConsumer = array();
			if ($tA['relevance']){
				$tConsumerIds = array();
				foreach ($tA['relevance'] as $k=>$v){
					if ( ! in_array($v['consumer_id'], $tConsumerIds)){
						$tConsumerIds[] = $v['consumer_id'];
					}
				}
				
				if ($tConsumerIds){
					$this->loadModel('ConsumerUserModel', 'mConsumer', 'consumer');
					$tConsumer = $this->mConsumer->getInfoByIds($tConsumerIds);
				}
			}
			
			//数据
			foreach ($tA['relevance'] as $k=>$v){
				$tA['relevance'][$k]['nickname'] = isset($tConsumer[$v['consumer_id']]) ? $tConsumer[$v['consumer_id']]['nickname'] : '';
				$tA['relevance'][$k]['portrait'] = isset($tConsumer[$v['consumer_id']]) ? $tConsumer[$v['consumer_id']]['portrait']['xs'] : '';
			}
		}
		
		//浏览记录
		
		//是否浏览
		if ( $tUser && ! $this->mFind->hasApproval($findId, $this->userId,2)){
			//浏览记录保存
			$save = true;
			$this->db->trans_begin();
			//点赞数+1
			if ( ! $this->mFind->save(array('read_number' => $tA['read_number'] + 1),$findId)){
				$this->db->trans_rollback();
				$save = false;
			}
			
			$data = array(
					'consumer_id'=>$this->userId,
					'find_id'=>$findId,
					'is_view'=>2,
					'addtime'=>time(),
			);
			
			if ( ! $this->mFind->saveApproval($data)){
				$this->db->trans_rollback();
				$save = false;
			}
			
			if ($save){
				$this->db->trans_commit();
			}
		}
		
		//评论列表
		$tA['comment'] = $this->mFind->appGetCommentList($findId,1,2);
		
		$this->appReturn(1,'',$tA);
	}
	
	public function getCommentList(){
		//表单验证
		$vConf = array(
				array('find_id', '发现id', 'required|is_natural_no_zero'),
		);
		
		$this->formDataValidation($vConf);
		
		$findId = trim(post('find_id'));
		$page = trim(post('page'));
		
		$tA = $this->mFind->getInfo($findId);
		if ( ! $tA){
			$this->appReturn(0,'数据不存在');
		}
		
		$tA = $this->mFind->appGetCommentList($findId,$page);
		if ( ! $tA){
			$this->appReturn(1,'没有评论');
		}
		$this->appReturn(1,'',$tA);
	}
	
	/**
	 * 评论发现
	 */
	public function saveComment(){
		//表单验证
		$vConf = array(
				array('find_id', '发现id', 'required|is_natural_no_zero'),
				array('content', '发现内容', 'required'),
		);
		
		$this->formDataValidation($vConf);
		
		$findId = trim(post('find_id'));
		$content = trim(post('content'));
		$comment_id = trim(post('comment_id'));
		
		$tA = $this->mFind->getInfo($findId);
		if ( ! $tA){
			$this->appReturn(0,'数据不存在');
		}
		//获取该条信息
        $maxId = 0;
		if ($comment_id){
            $tComment = $this->mFind->getCommentInfo($comment_id);
            if ($tComment){
                $maxId = $tComment['max_parent_id'];
            }
        }

		$data = array(
				'parent_id'=>$comment_id,
				'find_id'=>$findId,
				'consumer_id'=>$this->userId,
				'content'=>base64_encode($content),
				'good'=>0,
				'addtime'=>time(),
				'max_parent_id'=>$maxId,
				'status'=>1,
		);
		
		if ( ! $tId = $this->mFind->saveComment($data)){
			$this->appReturn(0,'评论失败');
		}
		//更新父级id
        if ( ! $comment_id){
		    //第一条评论则用自己id
            if ( ! $this->mFind->saveComment(array('max_parent_id'=>$tId),$tId) ){
                $this->appReturn(0,'评论失败');
            }
        }

		$this->appReturn(1,'评论成功');
	}

	/**
	 * 给发现点赞
	 */
	public function findApproval(){
		//表单验证
		$vConf = array(
				array('find_id', '发现id', 'required|is_natural_no_zero'),
		);
		
		$this->formDataValidation($vConf);
		
		$findId = trim(post('find_id'));
		
		$tA = $this->mFind->getInfo($findId);
		if ( ! $tA){
			$this->appReturn(0,'点赞失败');
		}
		
		//已经点过
		$this->db->trans_begin();
		if ($this->mFind->hasApproval($findId, $this->userId)){
			//$this->appReturn(0,'已经点过赞');
			//点赞数-1
			if ( ! $this->mFind->save(array('approval' => $tA['approval'] - 1),$findId)){
				$this->db->trans_rollback();
				$this->appReturn(0,'点赞失败');
			}
			
			//点赞记录保存
			if ( !$this->mFind->saveApproval(array('is_approval'=>NULL),$findId,$this->userId)){
				$this->db->trans_rollback();
				$this->appReturn(0,'点赞失败');
			}
			
			$this->db->trans_commit();
			$this->appReturn(1,'取消成功',['is_approval'=>"1"]);
		}else{
			
			//点赞数+1
			if ( ! $this->mFind->save(array('approval' => $tA['approval'] + 1),$findId)){
				$this->db->trans_rollback();
				$this->appReturn(0,'点赞失败');
			}
			
			//点赞记录保存
			if ( !$this->mFind->saveApproval(array('is_approval'=>2),$findId,$this->userId)){
				$this->db->trans_rollback();
				$this->appReturn(0,'点赞失败');
			}
			$this->db->trans_commit();
			$this->appReturn(1,'点赞成功',['is_approval'=>"2"]);
		}
		
	}

	/**
	 * 获取我发布的发现
	 */
	public function getMyFindList(){
        $this->loadModel('ConsumerFriendsCircleModel', 'mFriends', 'consumer');
		//表单验证
		$vConf = array(
				array('page', '分页', 'required|is_natural_no_zero'),
		);
		$this->formDataValidation($vConf);
		
		$page = post('page');
		
		$tA = $this->mFind->appGetMyList($this->userId,$page);
		if ( ! $tA){
			$this->appReturn(1,'未发布任何信息');
		}

		$data = array(
		    'list' => $tA['list'],
		    'find_count' => $tA['total'],
            'friends_count' => $this->mFriends->getTotal($this->userId),
        );

		$this->appReturn(1,'',$data);
	}

    /**
     * 获取他发布的发现
     */
    public function getOthersFindList(){
        $this->loadModel('ConsumerFriendsCircleModel', 'mFriends', 'consumer');
        //表单验证
        $vConf = array(
            array('page', '分页', 'required|is_natural_no_zero'),
            array('id', '他的id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf);

        $page = post('page');
        $id = post('id');

        $tA = $this->mFind->appGetMyList($id,$page);

        $info = $this->mUser->getInfo($id);

        $data = array(
            'list' => $tA['list'],
            'find_count' => $tA['total'],
            'friends_count' => $this->mFriends->getTotal($id),
            'userMobile' => substr($info['mobile'], 0, 3).'****'.substr($info['mobile'],-4)
        );

        $this->appReturn(1,'',$data);
    }

	/**
	 * 移除我发布的发现
	 */
	public function rmMyFind(){
		//表单验证
		$vConf = array(
				array('find_id', '发现id', 'required|is_natural_no_zero'),
		);
		
		$this->formDataValidation($vConf);
		
		$findId = trim(post('find_id'));
		
		$tA = $this->mFind->getInfo($findId);
		if ( ! $tA){
			$this->appReturn(0,'该信息不存在');
		}
		
		//验证用户
		if ($tA['consumer_id'] != $this->userId){
			$this->appReturn(0,'你不能删除该信息');
		}
		
		$this->db->trans_begin();
		
		if ( ! $this->mFind->save(array('is_delete'=>2),$findId)){
			$this->db->trans_rollback();
			$this->appReturn(0,'删除失败');
		}
		
		$this->db->trans_commit();
		$this->appReturn(1,'删除成功');
	}
	
	/**
	 * 获取特殊属性分类
	 */
	public function appAttribute(){
		//表单验证
		$vConf = array(
				array('category_id', '分类', 'required|is_numeric'),
		);
		$this->formDataValidation($vConf);
		
		$category_id = post('category_id');
        $tA = array();
		if($category_id > 0){
            $tA = $this->mAttribute->getList($category_id);
        }

		$this->appReturn(1,'',$tA);
	}
	
}
	